package com.yc.thread;

/**
 * @program: concurrent
 * @description: 死锁
 * @author: zy
 * @create: 2022-01-10 21:27
 */
public class Test16_deadLock implements Runnable {

    public int flag = 1;

    static Object o1 = new Object(), o2 = new Object();   //创建两个对象，以使用其两个对象锁

    public static void main(String[] args) {
        Test16_deadLock td1 = new Test16_deadLock();
        Test16_deadLock td2 = new Test16_deadLock();
        td1.flag = 1;
        td2.flag = 0;
        Thread t1 = new Thread(td1);
        Thread t2 = new Thread(td2);
        t1.start();
        t2.start();
    }

    @Override
    public void run() {
        System.out.println("flg=" + flag);
        if (flag == 1) {
            synchronized (o1) {   //第一线程执有o1锁
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (o2) {     //又想拿o2.
                    System.out.println("1");
                }
            }
        }
        if (flag == 0) {
            synchronized (o1) {    //第二线程执有o2锁
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (o2) {    //又想拿o1
                    System.out.println("0");
                }
            }
        }
    }
}

